<?php

class Core_Model_Contest extends YouNet_Db_Table_Row implements Core_Model_IContest
{
	const USING_CAPTCHA = 1;
	const NOT_USING_CAPTCHA = 0;
	
    const NEED_LIKE_FANPAGE = 1;
	const DONT_NEED_LIKE_FANPAGE = 0;
    
	const ABOUT_VIEW = 0;
	const ENTRIES_VIEW = 1;
	
	private $_currentTime;

	private $_isAllowMessage = array();

	protected $_spanTime = array();

	public function init()
	{
		parent::init();
		$this->_currentTime = time() + ((int)$this->time_zone*3600);

		if( empty($this->_data['time_created']) )
		{
			$this->time_created = time();
		}
		if (!isset($this->_data['status']))
		{
			$this->status = self::STATUS_HIDDEN;
		}
		$this->time_modified = time();
	}
    
    public function getLanguage()
    {
        $language = 'en_US';
        if(isset($this->language))
        {
            $language = $this->language;
        }
        return $language;
    }        
    
    public function isHasWinnerMessage()
    {
        if (isset($this->template_congratulation))
        {
            $message = $this->template_congratulation;
            $not_empty_validator = new YouNet_Validate_NotEmpty(array('type' => YouNet_Validate_NotEmpty::RICHTEXT));

            if ($not_empty_validator->isValid($message))
            {
                return true;
            }
        }
        return false;
    }

	/**
	 *
	 */
	public function getStatusLabel()
	{
		if( !$this->isFinished() )
		{
			return 'STATUS_LABEL_DRAFTED';
		}
		if( $this->status == self::STATUS_HIDDEN )
		{
			if( $this->isWaiting() )
			{
				return 'STATUS_LABEL_DRAFTED';
			}
			if( $this->isRunning() )
			{
				return 'STATUS_LABEL_HIDDEN';
			}
			return 'STATUS_LABEL_CLOSED';
		}
		if( $this->status == self::STATUS_PUBLISHED )
		{
			if( $this->isWaiting() )
			{
				return 'STATUS_LABEL_WAITING';
			}
			if( $this->isRunning() )
			{
				return 'STATUS_LABEL_RUNNING';
			}
			return 'STATUS_LABEL_END';
		}
		return 'STATUS_LABEL_DRAFTED';
	}
		
	public function setIsPublished()
	{
		$this->setStatus(self::STATUS_PUBLISHED);
		return $this;
	}

	public function setIsHidden()
	{
		$this->setStatus(self::STATUS_HIDDEN);
		return $this;
	}

	public function setIsReportAbuse()
	{
		$this->is_report_abuse = 1;
	}

	/**
	 * Check if a contest is draft
	 * @return boolean
	 */
	public function isDrafted()
	{
		throw new Exception('Not yet implemented');
	}

	/**
	 * Check if a contest is published
	 * @return boolean
	 */
	public function isPublished()
	{
		return $this->status == self::STATUS_PUBLISHED;
	}

	public function isNeedForApprove()
	{
		return $this->is_wait_for_approve;
	}

	/**
	 *
	 * @return Zend_Db_Table_Rowset
	 */
	public function getPrizesList()
	{
		return $this->findDependentRowset('Core_Model_DbTable_Prizes');
	}

	/**
	 *
	 * @return Zend_Db_Table_Rowset
	 */
	public function getPhasesList()
	{
		return $this->findDependentRowset('Core_Model_DbTable_Phases');
	}

	/**
	 *
	 * @return Zend_Db_Table_Rowset
	 */
	public function getListEntryFields()
	{
		return $this->findDependentRowset('Core_Model_DbTable_EntryFields');
	}

	public function getArrayPhaseForPopulate()
	{
		$phaseData		= array();
		$phaseList 		= $this->getPhasesList();
		if( count($phaseList) > 0 )
		{
			$phaseData		= $phaseList->toArray();
			for($i = 0; $i < count($phaseData); $i++)
			{
				$phaseData[$i]['options'] = array();
				foreach( array('is_allow_submit','is_allow_vote','is_allow_comment','is_allow_view') as $option )
				{
					if( $phaseData[$i][$option] == 1)
					{
						$phaseData[$i]['options'][]	= $option;
					}
				}
				$phaseData[$i]['date_start']	= date(YouNet_Util::translate('DATE_FORMAT'),$phaseData[$i]['date_start']);
				$phaseData[$i]['date_end']		= date(YouNet_Util::translate('DATE_FORMAT'),$phaseData[$i]['date_end']);
			}
		}
		return $phaseData;
	}

	/**
	 *
	 * @param type $id_user
	 * @param array $arr_id_pages
	 * @return boolean
	 */
	public function hasAdminPermission($id_user,array $arr_id_pages = null)
	{
		$isAdmin = false;
		if( $this->id_user == $id_user )
		{
			$isAdmin = true;
		}
		else
		{
			if( !empty($arr_id_pages) )
			{
				$arrIdPages = $this->getArrIdPages();
				if( !empty($arrIdPages) )
				{
					foreach($arrIdPages as $id_page)
					{
						if( in_array($id_page,$arr_id_pages) )
						{
							$isAdmin = true;
							break;
						}

					}
				}
			}
		}
		return $isAdmin;
	}

	/**
	 *
	 * @return boolean
	 */
	public function isAllowedSubmit()
	{
		//Cache for only one day
		$key	= Core_Cache_IKeys::MEMCACHE_CONTEST_IS_ALLOW_SUBMIT.$this->id;
		$value	= YouNet_Util::getMemCache()->load($key);
		if( $value === false )
		{
			$phases_db = Core_Model_DbTable_Phases::getInstance();
			if(!empty($this->id))
			{
				$value		= $phases_db->isAllowedSubmit($this)?1:0;
				$duration	= mktime(23, 59, 59) - $this->getCurrentTimeWithTZ();
				if( $duration > 0)
				{
					YouNet_Util::getMemCache()->save($value?1:0, $key, array(), $duration);
				}
				elseif( $duration < 0)
				{
					YouNet_Util::getMemCache()->save($value?1:0, $key, array(), $duration + 24*3600);
				}
			}
		}
		return $value;
	}

	/**
	 *
	 * @return boolean
	 */
	public function isAllowedView()
	{
		$key	= Core_Cache_IKeys::MEMCACHE_CONTEST_IS_ALLOW_VIEW.$this->id;
		$value = YouNet_Util::getMemCache()->load($key);
		if( $value === false)
		{
			$phases_db = Core_Model_DbTable_Phases::getInstance();
			if(!empty($this->id))
			{
				$value = $phases_db->isAllowedView($this)?1:0;
				$duration	= mktime(23, 59, 59) - $this->getCurrentTimeWithTZ();
				if( $duration > 0)
				{
					YouNet_Util::getMemCache()->save($value?1:0, $key, array(), $duration);
				}
				elseif( $duration < 0)
				{
					YouNet_Util::getMemCache()->save($value?1:0, $key, array(), $duration + 24*3600);
				}				
			}
		}
		return $value;
	}

	public function isAllowedVoteView()
	{
		$phases_db = Core_Model_DbTable_Phases::getInstance();
		$value = $phases_db->isAllowedVote($this) ? 1 : 0;
		return $value;
	}
	
	/**
	 * Check a user can vote for an entry or not
	 * @return boolean
	 */
	public function isAllowedVote($id_user, $id_entry)
	{
		$key	= Core_Cache_IKeys::MEMCACHE_USER_ENTRY_ALLOW_VOTE.$id_user.'_'.$id_entry;
		$value	= YouNet_Util::getMemCache()->load($key);
		if( $value === false || !$value)
		{
			$phases_db		= Core_Model_DbTable_Phases::getInstance();
			$votes_db		= new Core_Model_DbTable_Votes();

			$is_allow_vote		= false;
			$phase_allow_vote	= $phases_db->isAllowedVote($this);
			$vote_row			= $votes_db->findTheLastestVoteOfUser($id_entry, $id_user);
			$num_of_votes		= $votes_db->countUserVotesByContest($this->id, $id_user);

			if(!$phase_allow_vote)
			{
                $mgs = YouNet_Util::translate('MSG_PHASE_DOES_NOT_ALLOW_TO_VOTE');
                if($this->isEnd()){
                    $mgs = sprintf(YouNet_Util::translate('MSG_CONTEST_IS_ENDED'), $this->getEndDate(YouNet_Util::translate('DATE_FORMAT')));
                }
				
				$this->appendIsAllowedMessage($mgs);
			}
            else
            {

                /**
                * if user didn't vote for any entry
                * OR
                * this contest allow multi vote
                * THEN
                * if user didn't vote for the entry yet
                */
                if($num_of_votes == 0 || $this->is_allow_multi_vote == 1)
                {
                    if($vote_row->is_voted == 0)
                    {
                        $is_allow_vote = true;
                    }
                    else
                    {
                        $mgs = YouNet_Util::translate('MSG_VOTED_ALREADY');
                        $this->appendIsAllowedMessage($mgs);
                    }
                }

                if($this->is_allow_multi_vote==0)
                {
                    $mgs = YouNet_Util::translate('MSG_DOES_NOT_ALLOW_MULTI_VOTE');
                    $this->appendIsAllowedMessage($mgs);
                }
            }
            
			$value		= $phase_allow_vote && $is_allow_vote;
			YouNet_Util::getMemCache()->save($value?1:0, $key, array());
		}
		return $value;
	}

	/**
	 *
	 * @return boolean
	 */
	public function isAllowedComment()
	{
		return $this->is_allow_comment;
	}
    public function isAutoPost()
	{
		return $this->is_auto_post;
	}

	public function hasUserSubmited($id_user)
	{
		$entriesTable = new Core_Model_DbTable_Entries();
		return $entriesTable->countEntryByUser($id_user, $this->id);
	}

	/**
	 *
	 * @return Zend_Db_Table_Rowset
	 */
	public function getPagesList()
	{
		$data = YouNet_Util::getMemCache()->load(Core_Cache_IKeys::MEMCACHE_CONTEST_ID_PAGES.$this->id);
		if( $data === false)
		{
			$data = $this->findDependentRowset('Core_Model_DbTable_Pages');
			YouNet_Util::getMemCache()->save($data, Core_Cache_IKeys::MEMCACHE_CONTEST_ID_PAGES.$this->id);
		}
		return $data;
	}
    
    public function getPageName($id_page)
    {
        $page_name = "";
        $page_list = $this->getPagesList();
        foreach ($page_list as $page)
        {
            if($page['id_page'] == $id_page)
            {
                $page_name = $page['name_page'];
                break;
            }
        }
        return $page_name;
    }  
    public function getShareUrlSocialNetworks($params = array(), $is_facebook = true) {
        $social = YouNet_Api::getInstance()->getSocialPlugin();
        $params = array_merge(array(
			'module'		=> 'contest',
			'controller'	=> 'share',
			'action'		=> 'contest',
			'id_contest'	=> $this->id,
			'id_page'		=> $social->getIdPage()),$params);
        if( $is_facebook )
        {
            return $social->getShareUrl($params,'default',true);
        }
        $viewInstace	= Zend_Layout::getMvcInstance()->getView();
        return $viewInstace->serverUrl($viewInstace->url($params, 'default'));
    }
    public function getInviteUrlSocialNetworks($params = array()) {
        $social = YouNet_Api::getInstance()->getSocialPlugin();
        $params = array_merge(array(
			'module'		=> 'contest',
			'controller'	=> 'share',
			'action'		=> 'invite',
			'id_contest'	=> $this->id,
			'id_page'		=> $social->getIdPage()),$params);
        $viewInstace	= Zend_Layout::getMvcInstance()->getView();
        return $viewInstace->serverUrl($viewInstace->url($params, 'default'));
    }

	/**
	 * Get an array of id pages
	 * @return array
	 */
	public function getArrIdPages()
	{
		$arrReturn = array();
		$contestPageRowSet	= $this->getPagesList();
		if( $contestPageRowSet->count() )
		{
			foreach($contestPageRowSet as $contestPageRow)
			{
				$arrReturn[] = $contestPageRow->id_page;
			}
		}
		return $arrReturn;
	}

	/**
	 * @return type
	 * @deprecated Deprecated since version 1.0 by phutp
	 */
	public function getName()
	{
		trigger_error('The method getName() was deprecated as of '
                    . 'version 1.0, and may be removed. You\'re encouraged '
                    . 'to use getTitle() instead.');
		return $this->title;
	}

	/**
	 * @todo: This function must be replace by use min function of mysql (because date_start is indexed)
	 * @param string $format
	 * @return string
	 */
	public function getStartDate($format = DATE_FORMAT_HUMAN_DISPLAY)
	{
		$result = $this->_getTimeStart();
		if( !empty($result) )
		{
			return date($format,$result);
		}
		return 'n/a';
	}
	/**
	 *@return Integer
	 */
	public function _getTimeStart()
	{
		$value = YouNet_Util::getMemCache()->load(Core_Cache_IKeys::MEMCACHE_CONTEST_DATE_START.$this->id);
		if( $value === false)
		{
			if( empty($this->{self::SPAN_TIME_DATE_START}) )
			{
				$phaseTable		= Core_Model_DbTable_Phases::getInstance();
				$arrResult		= $phaseTable->getTimeSpan($this->id);
				if( !empty($arrResult[self::SPAN_TIME_DATE_START]) )
				{
					$value = $arrResult[self::SPAN_TIME_DATE_START];
				}
			}
			else
			{
				$value = $this->{self::SPAN_TIME_DATE_START};
			}
			YouNet_Util::getMemCache()->save($value,Core_Cache_IKeys::MEMCACHE_CONTEST_DATE_START.$this->id);
		}
		return $value;
	}

	/**
	 * @todo: This function must be replace by use max function of mysql (because date_end is indexed)
	 * @param string $format
	 * @return string
	 */
	public function getEndDate($format = DATE_FORMAT_HUMAN_DISPLAY)
	{
		$result = $this->_getTimeEnd();
		if( !empty($result) )
		{
			return date($format,$result);
		}
		return 'n/a';
	}

	public function _getTimeEnd()
	{
		$value = YouNet_Util::getMemCache()->load(Core_Cache_IKeys::MEMCACHE_CONTEST_DATE_END.$this->id);
		if( $value === false)
		{
			if( empty($this->{self::SPAN_TIME_DATE_END}) )
			{
				$phaseTable		= Core_Model_DbTable_Phases::getInstance();
				$arrResult		= $phaseTable->getTimeSpan($this->id);
				if( !empty($arrResult[self::SPAN_TIME_DATE_END]) )
				{
					$value = $arrResult[self::SPAN_TIME_DATE_END];
				}
			}
			else
			{
				$value = $this->{self::SPAN_TIME_DATE_END};
			}
			YouNet_Util::getMemCache()->save($value,Core_Cache_IKeys::MEMCACHE_CONTEST_DATE_END.$this->id);
		}
		return $value;
	}

	public function getRegistrantNumber()
	{
		return $this->registrants;
	}

	public function getSubmissionNumber()
	{
		return $this->submissions;
	}
    
    public function getApprovedSubmissionNumber(){
        return Core_Model_DbTable_Entries::getInstance()->countApprovedSubmissionByContest($this->id);
    }

	/**
	 * Get 'background' image uri, it return UPLOAD_PATH/STORED_SUB_FOLDER/image_name
	 * Should use baseUrl help to render html
	 * @see Zend_View_Helper_BaseUrl::baseUrl()
	 * @return string
	 */
	public function getBackgroundImageUrl()
	{
		if(!empty($this->image_background))
		{
			return STATIC_URL . $this->_getImageUrl('image_background', FOLDER_BACKGROUND);
		}
		else
		{
			return 0;
		}
	}

	/**
	 * Get 'welcome/fangate' image uri, it return UPLOAD_PATH/STORED_SUB_FOLDER/image_name
	 * Should use baseUrl help to render html
	 * @see Zend_View_Helper_BaseUrl::baseUrl()
	 * @return string
	 */
	public function getWelcomeImageUrl()
	{
		return STATIC_URL . $this->_getImageUrl('image_welcome',FOLDER_WELCOME);
	}

	/**
	 * Get 'banner' image uri, it return UPLOAD_PATH/STORED_SUB_FOLDER/image_name
	 * Should use baseUrl help to render html
	 * @see Zend_View_Helper_BaseUrl::baseUrl()
	 * @return string
	 */
	public function getBannerImageUrl()
	{
		if(!empty($this->image_banner))
		{
			return STATIC_URL . $this->_getImageUrl('image_banner', FOLDER_BANNER);
		}
		else
		{
			return STATIC_URL . $this->_getImageUrl('image_banner', FOLDER_BANNER) . DEFAULT_IMAGE;
		}
	}
	
	/**
	 * Get 'banner' image uri, it return UPLOAD_PATH/STORED_SUB_FOLDER/image_name
	 * Should use baseUrl help to render html
	 * @see Zend_View_Helper_BaseUrl::baseUrl()
	 * @return string
	 */
	public function getBannerThumbUrl()
	{
		if(!empty($this->image_banner))
		{
			return STATIC_URL . $this->_getImageUrl('image_banner', FOLDER_THUMBNAIL);
		}
		else
		{
			return STATIC_URL . $this->_getImageUrl('image_banner', FOLDER_BANNER) . DEFAULT_IMAGE_THUMB;
		}
	}
    
    public function getSkinPath()
    {
        if (!empty($this->skin))
			return TEMPLATE_PATH . '/' . $this->skin;
		return '';
    }
    public function getSkinHref()
    {
        return Zend_Controller_Front::getInstance()->getBaseUrl() . '/contest/manage/downloadskin/id/' . $this->id;
    }        
    public function getSkinUrl()
	{
		return $this->_getCssSkinUrl('skin');
	}
	private function _getCssSkinUrl($name)
	{
		$media_image_path = '/media/skin/template';
		return "$media_image_path/".$this->{$name};
	}

	public function getTitle()
	{
		if( !empty($this->title) )
		{
			return $this->title;
		}
		else
		{
			return DEFAULT_TITLE;
		}
	}

	public function getBannerLink()
	{
		if( !empty($this->banner_link) )
		{
			if( stripos($this->banner_link,'http') === 0)
			{
				return $this->banner_link;
			}
			return '//'.$this->banner_link;
		}
		else
		{
			return DEFAULT_BANNER_LINK;
		}
	}

	public function getWelcomeImageLink()
	{
		$welcome_image_path = '/media/image/welcome/';
		if(!empty($this->image_welcome))
		{
			return STATIC_URL . $welcome_image_path . $this->image_welcome;
		}
		else
		{
			return STATIC_URL . $welcome_image_path . DEFAULT_WELCOME_IMAGE;
		}
	}

	private function _getImageUrl($name, $subFolder)
	{
		$media_image_path = '/media/image';
		return "$media_image_path/{$subFolder}/".$this->{$name};
	}

	private function _getArraySteps()
	{
		return $arrSteps = array(
			self::STEP_CREATE_DETAIL,
			self::STEP_TIMELINE,
			self::STEP_CREATE_ENTRY,
			self::STEP_SETTING_THEME
		);
	}

	private function _addStep($value)
	{
		$arrSteps = $this->_getArraySteps();
		if( !in_array($value,$arrSteps) )
		{
			throw new Exception('The value is not in the haystack');
		}
		$this->steps |= $value;
	}

	private function _removeStep($value)
	{
		$arrSteps = $this->_getArraySteps();
		if( !in_array($value,$arrSteps) )
		{
			throw new Exception('The value is not in the haystack');
		}
		$this->steps &= ~$value;
	}

	/**
	 *
	 * @param boolean $is_finished
	 * @return Core_Model_Contest
	 */
	public function setIsFinishedCreateDetail($is_finished = true)
	{
		if( $is_finished )
		{
			$this->_addStep(self::STEP_CREATE_DETAIL);
		}
		else
		{
			$this->_removeStep(self::STEP_CREATE_DETAIL);
		}
		return $this;
	}

	/**
	 *
	 * @return boolean
	 */
	public function isFinishedCreateDetail()
	{
		if( ($this->steps & self::STEP_CREATE_DETAIL) === self::STEP_CREATE_DETAIL )
			return TRUE;
		return FALSE;
	}

	/**
	 *
	 * @param boolean $is_finished
	 * @return Core_Model_Contest
	 */
	public function setIsFinishedCreateEntry($is_finished = true)
	{
		if( $is_finished )
		{
			$this->_addStep(self::STEP_CREATE_ENTRY);
		}
		else
		{
			$this->_removeStep(self::STEP_CREATE_ENTRY);
		}
		return $this;
	}

	/**
	 *
	 * @return boolean
	 */
	public function isFinishedCreateEntry()
	{
		if( ($this->steps & self::STEP_CREATE_ENTRY) === self::STEP_CREATE_ENTRY )
			return TRUE;
		return FALSE;
	}

	/**
	 *
	 * @param boolean $is_finished
	 * @return Core_Model_Contest
	 */
	public function setIsFinishedTimeline($is_finished = true)
	{
		if( $is_finished )
		{
			$this->_addStep(self::STEP_TIMELINE);
		}
		else
		{
			$this->_removeStep(self::STEP_TIMELINE);
		}
		return $this;
	}
	/**
	 *
	 * @return boolean
	 */
	public function isFinishedTimeline()
	{
		if( ($this->steps & self::STEP_TIMELINE) === self::STEP_TIMELINE )
			return TRUE;
		return FALSE;
	}
	/**
	 *
	 * @param boolean $is_finished
	 * @return Core_Model_Contest
	 */
	public function setIsFinishedSettingTheme($is_finished = true)
	{
		if( $is_finished )
		{
			$this->_addStep(self::STEP_SETTING_THEME);
		}
		else
		{
			$this->_removeStep(self::STEP_SETTING_THEME);
		}
		return $this;
	}
	/**
	 *
	 * @return boolean
	 */
	public function isFinishedSettingTheme()
	{
		if( ($this->steps & self::STEP_SETTING_THEME) === self::STEP_SETTING_THEME )
			return TRUE;
		return FALSE;
	}

	public function countFinishedSteps()
	{
		$iCount		= 0;
		$arrSteps	= $this->_getArraySteps();
		foreach($arrSteps as $step)
		{
			if( ($step & $this->steps) != 0 )
				$iCount++;
		}
		return $iCount;
	}

	public function isFinished()
	{
		$arrSteps	= $this->_getArraySteps();
		$n			= count($arrSteps);
		if( $this->countFinishedSteps() == $n)
		{
			return true;
		}
		return false;
	}

	public function isLimittedEdit($phase_start = null)
	{
		if( !$this->isFinished() )
			return false;
		if( $this->isFinishedTimeline() )
		{
			if( $this->isRunning())
			{
                if(!is_null($phase_start)){
                    if($this->_currentTime < $phase_start){
                        return false;
                    }
                }
				return true;
			}
			if( $this->isEnd() )
			{
				return true;
			}
		}
		return false;
	}
    public function isLimitEditFanpage()
	{
		if( $this->isPublished() )
		{
			return true;
		}		
		return false;
	}
	public function canEditFanpage()
	{
		if( !$this->isFinished() )
		{
			return true;
		}
		if( ($this->status == self::STATUS_HIDDEN) && $this->isWaiting() )
		{
			return true;
		}
		return false;
	}
	/**
	 *
	 * @param int $status
	 * @return Core_Model_Contest
	 */
	public function setStatus($status)
	{
		$this->status = $status;
		return $this;
	}

	/**
	 *
	 * @param type $arrSort
	 * @return Zend_Db_Select
	 */
	public function getSelectionApprovedEntries($arrSort)
	{
		$entryModel		= new Core_Model_DbTable_Entries();
		$selection		= $entryModel->getApprovedSelectionByIdContest($this->id, $arrSort);
		return $selection;
	}

	public function appendIsAllowedMessage($value)
	{
		array_push($this->_isAllowMessage, $value);
	}

	public function getIsAllowedMessage()
	{
		return $this->_isAllowMessage;
	}

	public function canPublished(array &$error = null)
	{
		$arr_id_pages = $this->getArrIdPages();
		if( !$this->isFinished() )
		{
			if( isset($error) )
			{
				$error[] = YouNet_Util::translate('ERROR_MGS_NOT_YET_FINISHED');
			}
			return false;
		}
		if( empty($arr_id_pages) )
		{
			//The contest must be pushlised on a fanpage before published
			if( isset($error) )
			{
				$error[] = YouNet_Util::translate('ERROR_MGS_NO_FANPAGE');
			}
			return false;
		}
		$isError		= false;
		$errorNamePage	= array();
		foreach($this->getPagesList() as $contestPageRow)
		{
			if( Core_Model_DbTable_Contests::getInstance()->hasContestIsPublished($contestPageRow->id_page) )
			{
				$errorNamePage[] = $contestPageRow->name_page;
				$isError = true;
			}
		}
		if( $isError )
		{
			if( isset($error) )
			{
				$error[] = sprintf(YouNet_Util::translate('ERROR_EXIST_A_FANPAGE'),  '<strong>"'.implode('"</strong>,&nbsp;<strong>"', $errorNamePage).'"</strong>');
			}
		}
		return !$isError;
	}

	public function isWaiting()
	{
		return ($this->_getTimeStart() == 0 || $this->_currentTime  < $this->_getTimeStart());
	}

	public function isEnd()
	{
		return ($this->_currentTime  > $this->_getTimeEnd());
	}

	public function isRunning()
	{
		return ($this->_currentTime > $this->_getTimeStart()) && ($this->_currentTime < $this->_getTimeEnd());
	}

	public function canApproved($id_entry)
	{
		if( $this->isAllowMultiSubmit() )
		{
			return true;
		}
		else
		{
			$entryTbl = new Core_Model_DbTable_Entries();
			$entryRow = $entryTbl->findOne($id_entry);
			if( ($entryTbl->countApprovedSubmissionByAPairUserAndContest($entryRow->id_user, $entryRow->id_contest)) > 0 )
			{
				return false;
			}
		}
		return true;
	}

	public function isAllowMultiSubmit()
	{
		return $this->is_allow_multi_submit;
	}
	
	public function doSaveBasic($id_user,$arrValues)
	{
		if( empty($this->id_user) )
		{
			$this->id_user = $id_user;
		}

		if( isset($arrValues['title']) )
		{
			$this->title					= $arrValues['title'];
		}
		if( isset($arrValues['description']) )
		{
			$this->description				= $arrValues['description'];
		}
		if( isset($arrValues['template_prize']) )
		{
			$this->template_prize			= $arrValues['template_prize'];
		}
		if( isset($arrValues['template_congratulation']) )
		{
			$this->template_congratulation	= $arrValues['template_congratulation'];
		}

		$basic_options      = !empty($arrValues['options'])?$arrValues['options']:array();
        $advance_options	= !empty($arrValues['advance_options'])?$arrValues['advance_options']:array();
        
        $options    = array_merge($basic_options,$advance_options);
		$arrOptions	= Contest_Form_Basic::GetOptionsArray($this->isLimittedEdit());
		foreach($arrOptions as $opt)
		{
			if( in_array($opt,$options) )
			{
				$this->$opt = 1;
			}
			else
			{
				$this->$opt = 0;
			}
		}
		$this->setIsFinishedCreateDetail(true);
	}
    
    public function doSaveThemSetting($arrValues, $form)
    {
//        Zend_Debug::dump($_POST);die;
        if( isset($arrValues['google_analytics_id']) )
		{
			$this->google_analytics_id	= $arrValues['google_analytics_id'];
		}
        if( isset($arrValues['notify_email']) )
		{
			$this->notify_email	= $arrValues['notify_email'];
		}
        if( isset($arrValues['language']) )
		{
			$this->language	= $arrValues['language'];
		}
		if( isset($arrValues['default_view']) )
		{
			$this->default_view	= $arrValues['default_view'];
		}
        if( isset($arrValues['default_sort']) )
		{
			$this->default_sort	= $arrValues['default_sort'];
		}
        if( isset($arrValues['banner_link']) )
        {
            $this->banner_link	= $arrValues['banner_link'];
        }
        if( isset($arrValues['is_need_to_like']) )
        {
            $this->is_need_to_like	= $arrValues['is_need_to_like'];
        }
        
        $imageBanner		= $form->getImageBannerName();
        $imageBackground	= $form->getImageBackgroundName();
        $imageWelcome		= $form->getImageWelcomeName();
        $skin               = $form->getCssSkinName();
        
        if( !empty($imageBanner) )
        {
            $this->image_banner			= $imageBanner;
        }
        else
        {
            if( !empty($_POST['is_delete_banner']) )
            {
                $this->image_banner	= '';
            }
        }

        if( !empty($imageBackground) )
        {
            $this->image_background		= $imageBackground;
        }
        else
        {
            if( !empty($_POST['is_delete_background']) )
            {
                $this->image_background	= '';
            }
        }
        if( !empty($imageWelcome) )
        {
            $this->image_welcome			= $imageWelcome;
        }
        else
        {
            if( !empty($_POST['is_delete_welcome']) )
            {
                $this->image_welcome	= '';
            }
        }
        if( !empty($skin) )
        {
            $this->skin			= $skin;
        }
        else
        {
            if( !empty($_POST['is_delete_skin']) )
            {
                $this->skin	= '';
            }
        }
    }
	
	public function exportEntries($active_sheet)
	{
		$arrHeader	= array(
			YouNet_Util::translate('EXPORT_HEADER_ENTRY_ID'),
			YouNet_Util::translate('EXPORT_HEADER_TITLE'),
			YouNet_Util::translate('EXPORT_HEADER_DESCRIPTION'),
			YouNet_Util::translate('EXPORT_HEADER_IMAGE'),
			YouNet_Util::translate('EXPORT_HEADER_UPLOADED_TIME'),
            YouNet_Util::translate('EXPORT_HEADER_UPLOADER_NAME'),
            YouNet_Util::translate('EXPORT_HEADER_UPLOADER_EMAIL'),
            YouNet_Util::translate('EXPORT_HEADER_UPLOADER_PROFILE'),
			YouNet_Util::translate('EXPORT_HEADER_VIEWS'),
			YouNet_Util::translate('EXPORT_HEADER_VOTES'),
			YouNet_Util::translate('EXPORT_HEADER_SHARES'),
			YouNet_Util::translate('EXPORT_HEADER_STATUS')
		);
		
        $this->_processing_header($arrHeader,$active_sheet);
		$entriesTbl = new Core_Model_DbTable_Entries();
        
        $allEntries = $entriesTbl->getAllEntriesByIdContest($this->id);
        $row  = 2;
        foreach($allEntries as $entry)
        {
            /*@var $entry Core_Model_Entry*/
            $arrData			= $entry->toArray();
            $this->_processing_data_entry($entry,$arrData);
            $this->_processing_data($arrData,$row,$active_sheet);
            $row = $row + 1;
        }
	}
	public  function _processing_header($arr_header,&$active_sheet)
    {
        $row = 1;
        $styleArray = array(
            'font' => array(
                'bold' => true,
            )
        );

        $col = 0 ;
        foreach ( $arr_header as $field )
        { 
            $active_sheet->setCellValueByColumnAndRow($col, $row, $field)->getStyleByColumnAndRow($col,$row)->applyFromArray($styleArray);
            $col =  $col + 1;
        }
        
    }
    private function _gender($iGender)
	{
		switch($iGender)
		{
			case 0:
				return 'male';
				break;
			case 1:
				return 'female';
				break;
			default:
				return '';
				break;
		}
	}
	public function exportRegistrants($active_sheet)
	{
        $time_zone	= (int)$this->time_zone * 3600;
		$contestTbl = new Core_Model_DbTable_Contests();
		
        $arrColumns		= array();
        $allRows		= $contestTbl->getAllRegistrantsByContestId($this->id,$arrColumns);
        $arrHeader		= array();
        foreach($arrColumns as $column)
        {
            $arrHeader[]	= YouNet_Util::translate($column);
        }
        $arrHeader[]	= YouNet_Util::translate('EXPORT_HEADER_REGISTRATION_DATE');
        $arrHeader[]	= YouNet_Util::translate('EXPORT_HEADER_NUMBER_OF_ENTRIES');
        

        $this->_processing_header($arrHeader,$active_sheet);
        $i_row  = 2; 
        $date   = new Zend_Date();
        $date_format = sprintf('%s %s, %s', Zend_Date::MONTH_NAME_SHORT, Zend_Date::DAY_SHORT, Zend_Date::YEAR);
        foreach($allRows as $row)
        {
            $arrData	= array();
            if( isset($row['FIELD_GENDER']) )
            {
                $row['FIELD_GENDER'] = $this->_gender($row['FIELD_GENDER']);					
            }
            else
            {
                $row['FIELD_GENDER'] = "";
            }

            if(!empty($row['country']))
            {
                $row['FIELD_COUNTRY'] = $row['country'];
                if($row['FIELD_COUNTRY']=='-1')
                {
                    $row['FIELD_COUNTRY'] = '';
                }
            }
            else
            {
                $row['FIELD_COUNTRY'] = "";
            }
            
            if( !empty($row[Core_Model_IEntryFields::FIELD_DATE_OF_BIRTH]) )
            {
                $date->set($row[Core_Model_IEntryFields::FIELD_DATE_OF_BIRTH]);
                $row[Core_Model_IEntryFields::FIELD_DATE_OF_BIRTH] = $date->toString($date_format);
            }

            foreach($arrColumns as $column)
            {
                $arrData[]	= $row[$column];
            }
            
            $arrData[]		= date('M d, Y',$row['time_uploaded']+$time_zone);
            $arrData[]		= $row['entries'];
            
            $this->_processing_data($arrData,$i_row,$active_sheet);

            $i_row = $i_row + 1;
        }
		
	}
	
	public function exportParticipants($active_sheet)
	{
        $time_zone	= (int)$this->time_zone * 3600;
		$votesTbl = new Core_Model_DbTable_Votes();
		
        $allRows		= $votesTbl->getAllVotersByContest($this->id)->toArray();
        $arrHeader		= array(
            YouNet_Util::translate('EXPORT_HEADER_FULLNAME'),
            YouNet_Util::translate('EXPORT_HEADER_PROFILE'),
            YouNet_Util::translate('EXPORT_HEADER_EMAIL'),
            YouNet_Util::translate('EXPORT_HEADER_GENDER'),
            YouNet_Util::translate('EXPORT_HEADER_PARTICIPANT_DATE'),
            YouNet_Util::translate('EXPORT_HEADER_VOTES')
        );

        $this->_processing_header($arrHeader,$active_sheet);
        $i_row = 2;
        foreach($allRows as $row)
        {
            $arrData	= array();				
            $arrData[]	= $row['name'];
            $arrData[]	= $row['link'];
            $arrData[]	= $row['email'];
            $arrData[]	= $row['gender'];
            $arrData[]	= date('M d, Y H:i:s',$row['time_voted']+$time_zone);;
            $arrData[]	= $row['votes'];

            $this->_processing_data($arrData,$i_row,$active_sheet);
            $i_row = $i_row + 1;
        }
		
	}
	private function _processing_data_entry($entry,&$arrData)
	{
		$time_zone	= (int)$this->time_zone * 3600;
		$arrData['status']			= YouNet_Util::translate($entry->getStatusLabel());
		$arrData['image']			= $entry->getSubmissionImageUrl();
		$arrData['time_uploaded']	= date('M d, Y H:i:s',$arrData['time_uploaded']+$time_zone);
		$arrData['title']			= str_replace('"', '""', $arrData['title']);
		$arrData['description']		= str_replace('"', '""', $arrData['description']);
	}
	public function _processing_data($arrData,$row,&$active_sheet)
    {
        $col = 0 ;
        foreach ($arrData as $cell_val)
        {
           $active_sheet->setCellValueByColumnAndRow($col, $row, $cell_val);
           $col = $col + 1;
        }
    }
	public function exportVoters($active_sheet)
	{
        $time_zone	= (int)$this->time_zone * 3600;
        
        $this->_processing_header(array(
            YouNet_Util::translate('EXPORT_HEADER_ENTRY_ID'),
			YouNet_Util::translate('EXPORT_HEADER_VOTED_TIME'),
			YouNet_Util::translate('EXPORT_HEADER_FACEBOOK_NAME'),
			YouNet_Util::translate('EXPORT_HEADER_EMAIL'),
			YouNet_Util::translate('EXPORT_HEADER_PROFILE'),
            YouNet_Util::translate('EXPORT_HEADER_GENDER')
            ),$active_sheet);
        
        
		$entriesTbl = Core_Model_DbTable_Entries::getInstance();
		$result		= $entriesTbl->select()
				->from(Core_Model_DbTable_Entries::TABLE_NAME,null)
				->columns('id')
				->where('id_contest = ?', $this->id)
				->query()->fetchAll(PDO::FETCH_NUM);
		$arrIds = array();
		foreach($result as $row)
		{
			$arrIds[] = $row[0];
		}
		
		if( !empty($arrIds) )
		{
			$entryVoteTbl = new Core_Model_DbTable_EntryVotes();
			$select = $entryVoteTbl->select()->setIntegrityCheck(false);
			$select->from(array('e' => Core_Model_DbTable_EntryVotes::TABLE_NAME), array('e.id_entry','e.time_voted','e.ip','e.id_ref_user'));
			$select->joinInner(array('u' => Core_Model_DbTable_Users::TABLE_NAME), 'u.id = e.id_user' , array('u.*'));
			$select->where('e.id_entry IN (?)', $arrIds);
			$select->order('e.id_entry ASC');
			$select->order('e.time_voted DESC');
			$stm = $select->query();

            $i_row  = 2;
            while($row = $stm->fetch())
            {
                  $this->_processing_data(array(
                    $row['id_entry'],
                    date('M d, Y H:i:s',$row['time_voted']+$time_zone),
                    $row['name'] ,
                    $row['email'],
                    $row['link'],
                    $row['gender']
                ),$i_row,$active_sheet);

                 $i_row = $i_row  +1;
            }
		}
		
	}
	
	public function save()
	{
		$isResult = parent::save();
		YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_MODEL_CONTEST.$this->id);
		YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_ID_PAGES.$this->id);
		YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_IS_ALLOW_SUBMIT.$this->id);
		YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_IS_ALLOW_VIEW.$this->id);
		
		foreach($this->getArrIdPages() as $id_page)
		{
			YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_PAPGE_WITH_CONTEST.$id_page);
		}
		
		Core_Util::getPageCache()->remove(Core_Cache_IKeys::PAGE_TAB_INDEX_ABOUT.$this->id);
		Core_Util::getPageCache()->remove(Core_Cache_IKeys::PAGE_TAB_INDEX_WINNER.$this->id);
		Core_Util::getPageCache()->remove(Core_Cache_IKeys::PAGE_TAB_INDEX_LIKE.$this->id);
		return $isResult;
	}
	
	public function getThanksYouMgsKey()
	{
		return Core_Util::THANK_YOU_MSG.'_'.$this->id;
	}
	
	public function getCurrentTimeWithTZ()
	{
		return $this->_currentTime;
	}     
    
	public function getDefaultTarget()
	{
		switch ($this->default_view) {
		case self::ABOUT_VIEW:
			return 'about';
			break;
		case self::ENTRIES_VIEW:
			return 'view';
			break;
		default:
			return 'about';
			break;
		}
	}
    /**
	 *
	 * @param array $arrFanpageIds
	 */
	public function updateFanpageProcess(array $arrFanpageIds, array $arrSocialPages)
	{
        $arrPublishedPageIds    = array();
        if( !$this->canEditFanpage() )
        {
            if( $this->isLimitEditFanpage() )
            {
                $arrUserPageIds			= YouNet_Api::getInstance()->getSocialPlugin()->getUserPageIds();
                $arrPublishedPageIds	= Core_Model_DbTable_Pages::getOtherPublishedPageIds($this->id, $arrUserPageIds);
            }
        }
        
		$contestPageTable	= new Core_Model_DbTable_Pages();
		foreach($arrSocialPages as $id_page => $page_name)
		{
			$contestPageRow					= $contestPageTable->findOne($id_page, $this->id);
			if( in_array($id_page, $arrFanpageIds) && !in_array($id_page, $arrPublishedPageIds) )
			{
				if( empty($contestPageRow) )
				{
					$contestPageRow				= $contestPageTable->createRow();
					//$contestPageRow->time_published	= time();
				}
				$contestPageRow->id_page		= $id_page;
				$contestPageRow->name_page		= $page_name;
				$contestPageRow->id_contest		= $this->id;
				$contestPageRow->save();
				$contestPageTable->removeCacheIdFormByIdPage($id_page);
                YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_ID_PAGES.$id_page);
			}
			else
			{
				if( !empty($contestPageRow) )
				{
					$contestPageRow->delete();
					$contestPageTable->removeCacheIdFormByIdPage($id_page);
                    YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_ID_PAGES.$id_page);
				}
			}
		}
        YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_ID_PAGES.$this->id);
	}
    
    public function initShareConfig($options)
    {
        $shareRow = Core_Model_DbTable_Shares::getInstance()->getShareConfig($this->id);
        if(empty($shareRow->id_contest)){
            $shareRow->saveShareConfig($options);
        }
    }
    
    public function updateShareConfig($arrValues, $form)
    {
        $options = array(
            'id_contest' => $this->id
        );
        $shareRow = Core_Model_DbTable_Shares::getInstance()->getShareConfig($this->id);
        
        if( isset($arrValues['share_title']) )
		{
			$options['title']	= $arrValues['share_title'];
		}
        if( isset($arrValues['share_description']) )
		{
			$options['description']	= $arrValues['share_description'];
		}
        if( isset($arrValues['using_image']) )
		{
			$options['using_image']	= $arrValues['using_image'];
		}
        
        $shareImage		= $form->getImageShareName();
        if( !empty($shareImage) )
        {
            $options['image']			= $shareImage;
        }
        else
        {
            if( !empty($_POST['is_delete_share_image']) )
            {
                $options['image']	= '';
            }
        }
        $shareRow->saveShareConfig($options);
    }
    
    public function getViewEntriesDefault()
    {
        $default_sort = Core_Model_DbTable_Entries::ENTRIES_LATEST;
        if(isset($this->default_sort)){
            $default_sort = $this->default_sort;
        }
        return $default_sort;
    }
    
    public function isViewEntryByTwoColumn()
    {
        if(!empty($this->is_two_column) && ($this->is_two_column == 1)){
            return true;
        }
        return false;
    }
    
    public function getSharedContent($id_page)
    {
        $shareRow = Core_Model_DbTable_Shares::getInstance()->getShareContent($this->id, $id_page);
        return array(
            'title' => $shareRow->getShareTitle(),
            'description' => $shareRow->getShareDescription()
        );
    }
}
